package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.cache.util.RedisKeys;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.vo.StrategyStatisVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("---------------初始化开始----------------");
        // 攻略的统计对象
        List<Strategy> list = strategyService.list();
        List<StrategyStatisVO> vos = new ArrayList<>();
        StrategyStatisVO vo = new StrategyStatisVO();
        // 用户攻略收藏列表
        List<UserInfo> list1 = userInfoService.list();
        //初始化统计数据
        for (Strategy strategy : list) {
            String strKey = RedisKeys.STRATEGY_STATIS_VO.join(strategy.getId());
            if (template.hasKey(strKey)) {
                continue;
            }
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            template.opsForValue().set(strKey, JSON.toJSONString(vo));
        }
        for (UserInfo userInfo : list1) {
            String user_favor = RedisKeys.USER_FAVOR.join(userInfo.getId());
            if (template.hasKey(user_favor)) {
                continue;
            }
            template.opsForValue().set(user_favor, JSON.toJSONString(userInfo.getFavor()));
        }
        System.out.println("---------------初始化结束----------------");
    }
}
